package config

import (
	"errors"
)

// This file contains example of custom configuration that can be loaded from the service's configuration.toml
// and/or the Configuration Provider, aka Consul (if enabled).
// For more details see https://docs.edgexfoundry.org/2.0/microservices/device/Ch-DeviceServices/#custom-configuration

// Example structured custom configuration types. Must be wrapped with an outer struct with
// single element that matches the top level custom configuration element in your configuration.toml file,
// 'SpinningCustom' in this example.
type ServiceConfig struct {
	SpinningCustom SpinningCustomConfig
}

// SpinningCustomConfig is example of service's custom structured configuration that is specified in the service's
// configuration.toml file and Configuration Provider (aka Consul), if enabled.
type SpinningCustomConfig struct {
	OffImageLocation string
	OnImageLocation  string
	Writable         SimpleWritable
}

// SimpleWritable defines the service's custom configuration writable section, i.e. can be updated from Consul
type SimpleWritable struct {
	DiscoverSleepDurationSecs int64
}

// UpdateFromRaw updates the service's full configuration from raw data received from
// the Service Provider.
func (sw *ServiceConfig) UpdateFromRaw(rawConfig interface{}) bool {
	configuration, ok := rawConfig.(*ServiceConfig)
	if !ok {
		return false //errors.New("unable to cast raw config to type 'ServiceConfig'")
	}

	*sw = *configuration

	return true
}

// Validate ensures your custom configuration has proper values.
// Example of validating the sample custom configuration
func (scc *SpinningCustomConfig) Validate() error {
	if len(scc.OnImageLocation) == 0 {
		return errors.New("SpinningCustom.OnImageLocation configuration setting can not be blank")
	}

	if len(scc.OffImageLocation) == 0 {
		return errors.New("SpinningCustom.OffImageLocation configuration setting can not be blank")
	}

	if scc.Writable.DiscoverSleepDurationSecs < 10 {
		return errors.New("SpinningCustom.Writable.DiscoverSleepDurationSecs configuration setting must be 10 or greater")
	}

	return nil
}
